package dao

import (
	"github.com/bitly/go-simplejson"
	"github.com/go-xorm/xorm"

	"im/errcode"
	"im/model"
	"im/service/orm"
)

type Channels interface {
	List() []model.ChannelsVisually
	ListConfigs() ([]ChannelsConfig, error)
	UpdateChannel(channelName string, m model.Channels) error
	DeleteChannel(name string) error
	Create(m model.Channels) error
}

func NewChannels() Channels {
	return channels{db: orm.GetDB()}

}

type channels struct {
	db *xorm.Engine
}

func (c channels) Create(m model.Channels) error {
	_, err := c.db.InsertOne(&m)
	if err != nil {
		return errcode.NewError(errcode.DaoFailed, err)
	}
	return nil
}

func (c channels) DeleteChannel(name string) error {
	_, err := c.db.Where("name=?", name).Delete(&model.Channels{})
	if err != nil {
		return errcode.NewError(errcode.DaoFailed, err)
	}
	return nil
}

func (c channels) List() []model.ChannelsVisually {
	var ms []model.Channels
	err := c.db.Find(&ms)
	if err != nil {
		errcode.NewError(errcode.DaoFailed, err)
		return nil
	}
	var mvs = []model.ChannelsVisually{}
	for _, row := range ms {
		mvs = append(mvs, row.ChannelsVisually)
	}
	return mvs
}

type ChannelsConfig struct {
	Id    int64            `json:"id"`
	Name  string           `json:"name"`
	Desc  string           `json:"desc"`
	Feeds *simplejson.Json `json:"feeds"`
}

func (c channels) ListConfigs() ([]ChannelsConfig, error) {
	var ccs = []ChannelsConfig{}
	var ms []model.Channels
	err := c.db.Find(&ms)
	if err != nil {
		err = errcode.NewError(errcode.DaoFailed, err)
		return ccs, err
	}
	for _, row := range ms {
		feeds, _ := simplejson.NewJson([]byte(row.Feeds))
		ccs = append(ccs, ChannelsConfig{
			Id:row.Id,
			Name:  row.Name,
			Desc:  row.Desc,
			Feeds: feeds,
		})
	}
	return ccs, nil
}
func (c channels) UpdateChannel(channelName string, m model.Channels) error {
	_, err := c.db.Where("name=?", channelName).Update(&m)
	if err != nil {
		err = errcode.NewError(errcode.DaoFailed, err)
		return err
	}
	return nil
}
